# -*- coding: utf-8 -*-

######################################################
## uTorrent - Version (v1.50)                       ##
######################################################

import  traceback,string,os,shutil
from    xbmcgui     import ListItem as xListItem
from    types       import *
from    time        import time     as tTime
from    re          import findall  as reFindall, compile as reCompile, DOTALL as reDotAll, search as reSearch
from    urllib      import quote    as UrlQuote
import  core

## Class to Control uTorrent..
class Controller:
    def __init__(self,win,PathName):
        self.win                    =   win
        self._                      =   self.win._
        self.ClearVars()
        self.Version                =   '1.50'
        self.Dir                    =   'uTorrent'
        self.Title                  =   'uTorrent'
        self.FileType               =   'torrent'
        self.win.Title              =   self.Title

        ## Azureus Network Info
        self.TIMEOUT                =   int(10.0)
        self.FILEHASH               =   ''
        self.IP                     =   '192.168.0.1'
        self.PORT                   =   '8080'
        self.USER                   =   'admin'
        self.PASS                   =   'admin'
        self.URL                    =   'http://%s/gui/'
        self.LoginType              =   'BASIC'
        
        ## New Labels to Toggle Through..
        self.DNLABEL_               =   ['CompPct',  'Size'   ,  'Ratio'  ,'UpSpeed'  , 'DownSpeed','Peers'   , 'Seeds']
        self.UPLABEL_               =   ['Ratio'  ,'Size'   ,  'UpSpeed'  , 'DownSpeed','Peers'   , 'Seeds',  'CompPct']
        
        self.KeyMenus               =   {'150': {'A':('Select/Action','','torrentmenu')             ,   \
                                                 'X':('Display Files','','showfiles')}              ,   \
                                         '250': {'A':('Select/Action','','torrentmenu')             ,   \
                                                 'X':('Display Files','','showfiles')}              ,   \
                                         '450': {'A':('Select/Action','','filemenu')                ,   \
                                                 'B':('Download Normal (All)','','all-normal')      ,   \
                                                 'X':('Back to Torrent View','','showtorrents')     ,   \
                                                 'Y':('Do Not Download (All)','','all-off')}        ,   \
                                         '16':  {'A':('Select/Action','','showentries')             ,   \
                                                 'B':('Set as Default','','setdefault')             ,   \
                                                 'X':('uTorrent Config','','configmenu')            ,   \
                                                 'Y':('System Config','','systemmenu')}             ,   \
                                         '17':  {'A':('Select/Action','','showentries')             ,   \
                                                 'B':('Set as Default','','setdefault')             ,   \
                                                 'X':('uTorrent Config','','configmenu')            ,   \
                                                 'Y':('System Config','','systemmenu')}             ,   \
                                         '26':  {'A':('Select/Action','','showentries')             ,   \
                                                 'B':('Set as Default','','setdefault')             ,   \
                                                 'X':('uTorrent Config','','configmenu')            ,   \
                                                 'Y':('System Config','','systemmenu')}             ,   \
                                         '27':  {'A':('Select/Action','','showentries')             ,   \
                                                 'B':('Set as Default','','setdefault')             ,   \
                                                 'X':('uTorrent Config','','configmenu')            ,   \
                                                 'Y':('System Config','','systemmenu')}             ,   \
                                         '46':  {'A':('Select/Action','','showentries')             ,   \
                                                 'B':('Set as Default','','setdefault')             ,   \
                                                 'X':('uTorrent Config','','configmenu')            ,   \
                                                 'Y':('System Config','','systemmenu')}             ,   \
                                         '47':  {'A':('Select/Action','','showentries')             ,   \
                                                 'B':('Set as Default','','setdefault')             ,   \
                                                 'X':('uTorrent Config','','configmenu')            ,   \
                                                 'Y':('System Config','','systemmenu')}             ,   \
                                         '0':   {'A':('Select/Action','','')}}


        ## Check against Read config data.        
        if not (self.win.Config.has_key(self.Title))                :
            self.win.Config[self.Title]               = {}
        if not (self.win.Config[self.Title].has_key('IP'))          :
            self.win.Config[self.Title]['IP']         = self.IP
        if not (self.win.Config[self.Title].has_key('PORT'))        :
            self.win.Config[self.Title]['PORT']       = self.PORT
        if not (self.win.Config[self.Title].has_key('USER'))        :
            self.win.Config[self.Title]['USER']       = self.USER
        if not (self.win.Config[self.Title].has_key('PASS'))        :
            self.win.Config[self.Title]['PASS']       = self.PASS
        if not (self.win.Config[self.Title].has_key('DNLABEL_'))    :
            self.win.Config[self.Title]['DNLABEL_']   = self.DNLABEL_[0]
        if not (self.win.Config[self.Title].has_key('UPLABEL_'))    :
            self.win.Config[self.Title]['UPLABEL_']   = self.UPLABEL_[0]
        if not (self.win.Config[self.Title].has_key('TIMEOUT'))     :
            self.win.Config[self.Title]['TIMEOUT']    = self.TIMEOUT

        ### Pass these Parameters Back for Ease ###
        if not self.win.Modules.has_key('Ctrl')             :   self.win.Modules['Ctrl']    =   {} 
        self.win.Modules['Ctrl'][self.Title]                =   {}
        self.win.Modules['Ctrl'][self.Title]['Path']        =   PathName
        self.win.Modules['Ctrl'][self.Title]['FileType']    =   self.FileType

        self.UpdateAll()
        

####################################################################################################################
######## START ###################### COMMUNICATION ################################################################      
####################################################################################################################

    def ClearVars(self) :
        self.Comms                  =   {}

    def UpdateAll(self) :
        self.UpdateUrl()
        self.UpdateLogin()
        self.UpdateTimeout(self.TIMEOUT)
        
        
    def UpdateUrl(self) :
        self.FullUrl                =   self.URL    %  \
                                        str(self.win.Config[self.Title]['IP'] +':'+ self.win.Config[self.Title]['PORT'])
        

    def UpdateLogin(self) :
        try :
            self.Login = ''
            if self.win.Config[self.Title].has_key('USER') and self.win.Config[self.Title].has_key('PASS')  :
                if self.win.Config[self.Title]['USER'] != '' and self.win.Config[self.Title]['PASS'] != ''  :
                    self.Login =    str(self.win.Config[self.Title]['USER']) +':'+ str(self.win.Config[self.Title]['PASS'])
        except:
            traceback.print_exc()
            self.Login = ''
            

    def UpdateTimeout(self,timeout) :
        try :
            self.TIMEOUT    =   int(self.win.Config[self.Title]['TIMEOUT'])
        except:
            traceback.print_exc()
            self.TIMEOUT    =   timeout


####################################################################################################################
######## START ###################### MAIN ######## ################################################################      
####################################################################################################################

    def GetDownloads(self):
        self.win.xPrint('--GetDownloads')

        ## If its the first run then build Flag file and run the config first..
        FLAGFILE    =   str(self.win.Ctrl_) + str(self.Dir) +'\\first.run'
        if not (os.path.isfile(FLAGFILE))    :
            self.win.xPrint('** Config Needs to be run **')
            f = open(FLAGFILE,"wb")
            f.close()
            self.SystemMenu()
        
        Data        =   {}
        ## Run selection Based on Uploads,Downloads, Or Files..
        if      self.win.ViewState      ==  self.win.STATE_DOWN     :
            self.win.SiteLabel          =   'uTorrent - Downloads ['+  str(self.win.Config[self.Title]['DNLABEL_']) +']'
            Data                        =   self.GetTorrents(self.win.Config[self.Title]['DNLABEL_'],'false',self.DNLABEL_)

        elif    self.win.ViewState      ==  self.win.STATE_UP       :
            self.win.SiteLabel          =   'uTorrent - Uploads ['+ str(self.win.Config[self.Title]['UPLABEL_']) +']'
            Data                        =   self.GetTorrents(self.win.Config[self.Title]['UPLABEL_'],'true',self.UPLABEL_)

        elif    self.win.ViewState      ==  self.win.STATE_FILES    :
            self.win.SiteLabel          =   'uTorrent - File Listing ['+ str(self.TORRENT) +']'
            Data                        =   self.GetFiles()
        self.win.xPrint('++GetDownloads')
        return Data       


    def GetTorrents(self,Label2,wanted,Extras):
        try :
            self.win.xPrint('--GetTorrents')
            ## Initialise Variables that will be passed back ##
            Tor                     =   {}
            Tor_Array               =   []
            Queue                   =   0
            GlobalMsg               =   ''

            ## Process the Command..
            Response    =   self.win.UrlThread(self.FullUrl            +'?list=1'              ,   \
                                               login=self.Login                                ,   \
                                               timeout=int(self.win.Config[self.Title]['TIMEOUT']))
            if Response ==  None    :   raise Exception

            ## Now execute the returned python list into a tmp Array called TAR..
            Tar                     =   {}
            exec('Tar='+ str(Response))
            
            ## Reset some temp variables.
            sp1                     =   0
            sp2                     =   0
            _tmp                    =   []
            
            for _a in Tar['torrents'] :
                if int(_a[4]) == 1000   :   tortype = 'true'
                else                    :   tortype = 'false'
                sp1                     +=  int(_a[9])
                sp2                     +=  int(_a[8])                
                if tortype == wanted    :
                    Nm                      =   str(_a[2])
                    Tor[Nm]                 =   {}
                    Tor[Nm]['Id']           =   str(_a[0])
                    Tor[Nm]['State']        =   str(_a[1])
                    Tor[Nm]['Size']         =   str((_a[3]/1024)/1024) +' MB'
                    Tor[Nm]['Ratio']        =   str(_a[7])[:-1].rjust(1,'0') +'.'+ str(_a[7])[-1:].rjust(1,'0')       +'%'
                    Tor[Nm]['Position']     =   int(_a[17])
                    Tor[Nm]['UpSpeed']      =   str(_a[8])[:-3].rjust(1,'0') +'.'+ str(_a[8])[-3:-1].rjust(2,'0')     +' kBs'
                    Tor[Nm]['DownSpeed']    =   str(_a[9])[:-3].rjust(1,'0') +'.'+ str(_a[9])[-3:-1].rjust(2,'0')     +' kBs'
                    Tor[Nm]['Peers']        =   str(_a[12])         +'('+ str(_a[13])       +')'
                    Tor[Nm]['Seeds']        =   str(_a[14])         +'('+ str(_a[15])       +')'
                    Tor[Nm]['CompPct']      =   str(_a[4])[:-1].rjust(1,'0') +'.'+ str(_a[4])[-1:].rjust(1,'0')       +'%'
                    _tmp.append([int(_a[17]),Nm])

                    ## Set Health Based on States..
                    Tor[Nm]['Health']       =   1   ## Default
                    if   ( int(_a[1]) & 1 ) :
                        if   ( int(_a[1]) & 32 )     :   Tor[Nm]['Health'] = 3 ##Paused - Yellow
                        elif ( int(_a[1]) & 64 )     :   Tor[Nm]['Health'] = 4 ##Running - Green
                        elif ( not int(_a[1]) & 64 ) :   Tor[Nm]['Health'] = 2 ##Forced Running - Blue
                    elif ( int(_a[1]) & 16 )         :   Tor[Nm]['Health'] = 5 ##Errors

            _tmp.sort()
            
            for Item in _tmp:
                Health_Img  =   self.win.MEDIA +'health-'+ str(Tor[Item[1]]['Health']) +'.png'

                ## Now Create Extra Information Tags to be displayed when focused.
                ExtraInf    =   ''
                for xtra in Extras  :
                    ExtraInf    +=   str(xtra)+':'+ str(Tor[Item[1]][str(xtra)])+ ' / '

                TORITEM     =   xListItem(Item[1],Tor[Item[1]][Label2],ExtraInf,Health_Img)
                Tor_Array.append(TORITEM)
            
            ## Get config and process it if it exists..
            Response    =   self.win.UrlThread(self.FullUrl            +'?action=getsettings'   ,   \
                                               login=self.Login                                ,   \
                                               timeout=int(self.win.Config[self.Title]['TIMEOUT']))
            if Response !=  None    :   
                Tar                     =   {}
                exec('Tar='+ str(Response))
                UL = 0
                DL = 0
                for i in Tar['settings']:
                    if i[0] == 'max_dl_rate' :   DL = str(i[2])
                    if i[0] == 'max_ul_rate' :   UL = str(i[2])
                SP1         =   str(sp1)[:-3].rjust(1,'0') +'.'+ str(sp1)[-3:-1].rjust(2,'0')      
                SP2         =   str(sp2)[:-3].rjust(1,'0') +'.'+ str(sp2)[-3:-1].rjust(2,'0')      
                DnStat      =   'Downloads: ['+ DL +'K] '+ str(SP1) +' Kb/s'
                UpStat      =   'Uploads: ['+ UL +'K] '+ str(SP2) +' Kb/s'            
                GlobalMsg   =   DnStat +' - '+ UpStat
                
            self.win.xPrint('++GetTorrents')            
            return {'Torrents':Tor,'TorListItem':Tor_Array,'Queue':Queue,'GlobalMsg':GlobalMsg}         
        except:
            traceback.print_exc()
            self.win.xPrint('==GetTorrents')            
            return None


    def GetFiles(self) :
        try :
            self.win.xPrint('--GetFiles')
            ## Initialise Temp Variables
            Tor                     =   {}
            Tor_Array               =   []
            GlobalMsg               =   ''
            
            ## Process the Command..
            ActionUrl       =   str(self.FullUrl + '?action=getfiles&hash=%s') % str(self.FILEHASH) 
            Response    =   self.win.UrlThread(ActionUrl                                        ,   \
                                               login=self.Login                                 ,   \
                                               timeout=int(self.win.Config[self.Title]['TIMEOUT']))
            if Response ==  None    :   raise Exception

            ## Now execute the returned python list into a tmp Array called fdata.
            exec('fdata='+ str(Response))

            if len(fdata['files']) == 2 :
                for No in range(len(fdata['files'][1]))   :
                    Array               =   fdata['files'][1][No]
                    Nm                  =   str(Array[0])
                    Tor[Nm]             =   {}
                    Tor[Nm]['Size']     =   self.NiceSize(int(Array[1]))
                    Tor[Nm]['Idx']      =   str(No)
                    if      int(Array[3])   ==  0   :   Health = 5
                    elif    int(Array[3])   ==  1   :   Health = 3
                    elif    int(Array[3])   ==  2   :   Health = 4
                    elif    int(Array[3])   ==  3   :   Health = 2
                    else                            :   Health = 1
                    Tor[Nm]['Health']   =   str(Health)
                    Health_Img  =   self.win.MEDIA +'health-'+ str(Health) +'.png'
                    TORITEM     =   xListItem(str(Nm),str(Tor[Nm]['Size']),'No Additional Info',Health_Img)
                    Tor_Array.append(TORITEM)

                GlobalMsg      =   str(self.TORRENT)
                self.win.xPrint('++GetFiles')            
                return {'Torrents':Tor,'TorListItem':Tor_Array,'GlobalMsg':GlobalMsg}                         
            else    :
                raise Exception
        except:
            traceback.print_exc()
            self.win.xPrint('==GetFiles')
            return None


    def NiceSize(self,Size) :
        try :
            Loops   =   0
            Arr     =   [' BYTES',' KB',' MB',' GB',' TB']
            while Size > 1024 :
                Size    =   Size / 1024
                Loops   =   Loops + 1
            return str(Size) + str(Arr[Loops])
        except:
            traceback.print_exc()
            return 'Unknown'
            
                
####################################################################################################################
######## START ###################### TORRENT/FILE ACTIONS #########################################################      
####################################################################################################################

    def KeyAction(self,Buttons,Labels):
        try :
            self.win.xPrint('--KeyAction: '+ str(Labels) +'-'+ str(Buttons))
            Action      =   Buttons[2]
            Options     =   []
            
            ## Display Menu additional Options
            if      Action      ==  'torrentmenu'   :
                Result = self.TorrentMenu(Labels[0])
                if ( Result )   :   return True,True
                else            :   return False,False

            ## Global Configuration Options
            elif    Action      ==  'configmenu'    :
                Result = self.ConfigMenu()
                if ( Result )   :   return True,True
                else            :   return False,False

            ## System Options
            elif    Action      ==  'systemmenu'    :
                self.SystemMenu()
                return True,False

            ## Files Menu Options
            elif    Action      ==  'filemenu'      :
                Result  =   self.FileMenu(Labels[0])
                if ( Result )   :   return True,True
                else            :   return False,False

            ## Set as Default
            elif    Action      ==  'setdefault'    :
                self.win.SetDefault(self.Title)
                return True,False

            ## Switch to Files View for the Torrent
            elif    Action      == 'showfiles'      :
                self.ViewState      =   self.win.ViewState
                self.win.ViewState  =   self.win.STATE_FILES
                self.FILEHASH       =   str(self.win.Torrents[Labels[0]]['Id'])
                self.TORRENT        =   str(Labels[0])
                return True,True

            ## Switch to Torrents View.
            elif    Action      ==  'showtorrents'  :
                self.win.ViewState  =   self.ViewState
                self.FILEHASH   =   ''
                self.TORRENT    =   ''
                return True,True
                
            ## Change all File entries for the Torrent
            elif    Action[:4]  ==  'all-'  :
                if  Action[4:]  ==  'off'   :   Pri     =   0
                else                        :   Pri     =   2
                URL             =   self.FullUrl + '?action=setprio&hash='+ str(self.FILEHASH) +'&p=' + str(Pri)
                FILE            =   '&f=%s'
                for Key in self.win.Torrents.keys() :
                    URL     =   str(URL + FILE)     %   str(self.win.Torrents[Key]['Idx'])

                ## Process the Command..
                Response    =   self.win.UrlThread(URL                                              ,   \
                                                   login=self.Login                                 ,   \
                                                   timeout=int(self.win.Config[self.Title]['TIMEOUT']))
                if Response ==  None    :   raise Exception
                else                    :   return True,True

            ## Nothing To Do..
            self.win.xPrint('Cant Find anything to do.')            
            self.win.xPrint('++KeyAction')
            return True,False
        except :
            traceback.print_exc()    
            self.win.UpdateProgress(self._[31],-1)
            self.win.xPrint('==KeyAction')
            return False,False


    def FileMenu(self,Label): 
        try :
            self.win.xPrint('--FileMenu')
            ## Setup Variables
            URL             =   self.FullUrl + '?action=setprio&hash='+ str(self.FILEHASH)
            PRI             =   '&p=%s'
            FILE            =   '&f=%s'
            Options         =   [[self._[70],0],[self._[71],1],[self._[72],2],[self._[73],3]]
            MenuList        =   []

            ## Create Menu
            for List in Options     :
                MenuList.append(List[0])
            Answer          =   self.win.Menu.select(self._[14],MenuList)

            ## Process Answer
            if Answer != -1 :
                NewPri      =   str(PRI)    %   str(Options[Answer][1])
                NewFile     =   str(FILE)   %   str(self.win.Torrents[Label]['Idx'])
                FullUrl     =   str(URL) + str(NewPri) + str(NewFile)
                ## Process the Command..
                Response    =   self.win.UrlThread(FullUrl                                          ,   \
                                                   login=self.Login                                 ,   \
                                                   timeout=int(self.win.Config[self.Title]['TIMEOUT']))
                if Response ==  None    :   raise Exception
                else                    :   return True

            self.win.xPrint('++FileMenu')
            return True
        except:
            traceback.print_exc()
            self.win.xPrint('==FileMenu')
            return False


    def TorrentMenu(self,Label): 
        try :
            self.win.xPrint('--Torrent Menu')

            ## Available Local Options:
            Options = []
            Rec     = self.win.Torrents[Label]
            State   = int(Rec['State'])
            
            if not (State & 1)  :   Options.append([self._[5] ,'?action=start&hash=%s',''])
            else                :   Options.append([self._[6] ,'?action=stop&hash=%s',''])
            if (State & 1) and (State & 64)         :
                Options.append([self._[42],'?action=forcestart&hash=%s',''])
            elif (State & 1) and not (State & 64)   :
                Options.append([self._[42],'?action=start&hash=%s',''])                
            if not (State & 32) :   Options.append([self._[43],'?action=pause&hash=%s',''])
            else                :   Options.append([self._[45],'?action=start&hash=%s',''])            
            Options.append([self._[11],'?action=remove&hash=%s',''])
            Options.append([self._[44],'?action=removedata&hash=%s',''])

            ## Display Menu:
            MenuList = []
            for List in Options:    MenuList.append(List[0])
            Answer = self.win.Menu.select(self._[14],MenuList)

            ## Process answer
            if Answer != -1 :
                if      'remove'    in  Options[Answer][1]  :
                    YesNo = self.win.Menu.yesno(self._[17],self._[18],Label)
                    if not YesNo    :   self.win.xPrint('Dont do it!')
                ActionUrl   = str(self.FullUrl + Options[Answer][1]) % str(Rec['Id']) 
                ## Process the Command..
                Response    =   self.win.UrlThread(ActionUrl                                        ,   \
                                                   login=self.Login                                 ,   \
                                                   timeout=int(self.win.Config[self.Title]['TIMEOUT']))
                if Response ==  None    :   raise Exception
                else                    :   return True

            self.win.xPrint('Nothing to Update')
            self.win.xPrint('++Torrent Menu')
            return True
        except:
            traceback.print_exc()
            self.win.xPrint('==Torrent Menu')
            return False


    def ConfigMenu(self):
        try :
            self.win.xPrint('--ConfigMenu')            
            Options     =   []

            ## Get Config..
            Response    =   self.win.UrlThread(self.FullUrl            +'?action=getsettings'   ,   \
                                               login=self.Login                                ,   \
                                               timeout=int(self.win.Config[self.Title]['TIMEOUT']))
            if Response  ==  None    :   raise Exception

            ## Load the returned strings into the Cfg Dictionaries and reset standard variables..
            Cfg     =   {}
            Tvars   =   {}
            exec('Cfg='+ str(Response))

            ## Loop through the config and setup the variables..
            for i in Cfg['settings']    :
                if i[0] == 'max_ul_rate'            :   Tvars['max_ul_rate']            = str(i[2])
                if i[0] == 'max_dl_rate'            :   Tvars['max_dl_rate']            = str(i[2])
                if i[0] == 'conns_per_torrent'      :   Tvars['conns_per_torrent']      = str(i[2])
                if i[0] == 'conns_globally'         :   Tvars['conns_globally']         = str(i[2])
                if i[0] == 'max_active_downloads'   :   Tvars['max_active_downloads']   = str(i[2])
                if i[0] == 'max_active_torrent'     :   Tvars['max_active_torrent']     = str(i[2])

            ## Available Global Options:
            if      len(self.win.Torrents)  > 0     :
                Options.append([self._[19],'stopAllDownloads',''])
                Options.append([self._[20],'startAllDownloads',''])

            ## Core Parameter configuration Options.
            Options.append(['Modify - Max Upload Speed KBs'             ,'max_ul_rate',''])
            Options.append(['Modify - Max Download Speed KBs'           ,'max_dl_rate',''])
            Options.append(['Modify - Max Connections Per Torrent'      ,'conns_per_torrent',''])
            Options.append(['Modify - Max Connections Global'           ,'conns_globally',''])
            Options.append(['Modify - Max Downloads'                    ,'max_active_torrent',''])
            Options.append(['Modify - Max Active Torrents'              ,'max_active_downloads',''])

            ActionUrl   =   ''
            MenuList    =   []

            ## Display Menu:
            for List in Options     :
                MenuList.append(List[0])
            Answer = self.win.Menu.select(self._[14],MenuList)

            ## Process Answer
            if Answer != -1         :
                if MenuList[Answer][:9] == 'Modify - ' :
                    ## Core parameter change requested.
                    Param1  =   Options[Answer][1]
                    Param2  =   self.win.Menu.numeric(0,str(Options[Answer][0]) + \
                                                      ': ['+ str(Tvars[Param1]) +']')
                    if Param2 != -1 :
                        ActionUrl   =   str(self.FullUrl) + '?action=setsetting&s=' + Param1 +'&v=' + Param2 

                else                                    :
                    ## Stop/Start all currently displayed Items.
                    Hashs   =   ''
                    if  'stop'  in  str(Options[Answer][1]) :   xAct    =   'stop'
                    else                                    :   xAct    =   'start'
                    for i in self.win.Torrents.keys()       :
                        Hashs   +=  'hash='+    str(self.win.Torrents[i]['Id'])     +'&'
                    ActionUrl   =   str(self.FullUrl) +'?action='+ str(xAct) +'&'+ Hashs[:-1]
                    
                ## Perform the Action ..
                if ActionUrl != ''  :
                    Response    =   self.win.UrlThread(str(ActionUrl)                                   ,   \
                                                       login=self.Login                                 ,   \
                                                       timeout=int(self.win.Config[self.Title]['TIMEOUT']))
                    if Response  ==  None   :   raise Exception
                    else                    :   return True
                else                :
                    self.win.xPrint('Nothing to Update..')
                    return True

            self.win.xPrint('Update Cancelled..')
            self.win.xPrint('++ConfigMenu')
            return True
        except:
            traceback.print_exc()
            self.win.xPrint('==ConfigMenu')
            return False


    def SystemMenu(self):
        try :
            self.win.xPrint('--SystemMenu')
            OK = False
            while not ( OK )    :            
                ## Available Configurations for Controller..
                ## 0 =  Display Name,   1 = Variable Name,  2 = Variable Type.
                Config      =   [['IP Address ['    + str(self.win.Config[self.Title]['IP'])        +']' ,'IP'       ,'IP']  , \
                                 ['Timeout ['       + str(self.win.Config[self.Title]['TIMEOUT'])   +']' ,'TIMEOUT'  ,'INT'] , \
                                 ['PORT Number ['   + str(self.win.Config[self.Title]['PORT'])      +']' ,'PORT'     ,'INT'] , \
                                 ['Username ['      + str(self.win.Config[self.Title]['USER'])      +']' ,'USER'     ,'TXT'] , \
                                 ['Password ['      + str(self.win.Config[self.Title]['PASS'])      +']' ,'PASS'     ,'TXT'] , \
                                 ['**** DONE ****'  ,'OK','OK']]
                
                ## Display Menu.
                MenuList            =   []
                for List in Config  :
                    MenuList.append(List[0])
                Answer = self.win.Menu.select(self._[14],MenuList)

                ## Now work on the Results.
                if Answer != -1         :
                    Result  =   -1
                    if      Config[Answer][2]   ==  'IP'    :
                        Result  =   self.win.Menu.numeric(3,str(MenuList[Answer]) +': ['+ \
                                                          str(self.win.Config[self.Title][Config[Answer][1]]) +']')

                    elif    Config[Answer][2]   ==  'INT'   :
                        Result  =   self.win.Menu.numeric(0,str(MenuList[Answer]) +': ['+ \
                                                          str(self.win.Config[self.Title][Config[Answer][1]]) +']')

                    elif    Config[Answer][2]   ==  'TXT'   :
                        Result  =   self.win.KeyText(str(self.win.Config[self.Title][Config[Answer][1]]),str(MenuList[Answer]))

                    elif    Config[Answer][2]   ==  'OK'   :
                        OK = True
                        
                    if Result == -1 or Result == '' :
                        self.win.xPrint('-1 or empty return so dont update it..')
                    else                            :
                        ## Clear the Cookie, Reset the Variables and Update config item..
                        #core.ClearCookie(str(self.win.Config[self.Title]['IP']))
                        self.win.Config[self.Title][Config[Answer][1]] = str(Result)
                        self.ClearVars()
                        self.UpdateAll()
                        self.win.ResetVars()
                else                    :
                    OK = True
            self.win.xPrint('++SystemMenu')
        except:
            traceback.print_exc()
            self.win.xPrint('==SystemMenu')
              

####################################################################################################################
######## START ###################### TORRENTS ADDED AND LISTED ####################################################      
####################################################################################################################

############################################################################################
## THIS IS THE REAL CODE I WANTED TO USE BUT FOR SOME REASON ALTHOUGH IT WORKS.
## ON PYTHON RUN VIA THE PC IT FAILS WHEN RUN ON THE XBOX. THE CONNECTION APPEARS
## TO GET CUT-OFF MID CONNECTION AND AND ERROR IS REPORTED BACK. THE A RESPONSE
## OF PEER RESET CONNECTION OCCURS. I BELIEVE DUE TO THE FACT THAT WERE STILL TRYING
## TO SEND DATA.
## I SUSPECT THE PROBLEM IS SOMETHING TODO WITH HOW THE XBOX READS THE BINARY FILE FILE.
############################################################################################

##    def SendTorrent(self,LookDir,TorrentFile)   :
##        try     :
##            self.win.xPrint('--SendTorrent')
##            ## Read file data..
##            realfile        =   LookDir + TorrentFile
##            f               =   open(realfile,'rb')
##            fdata           =   f.read()
##            f.close()
##
##            ## Create post data..                        
##            print 'Pre  Post-Data is :' + str(len(fdata)) +' Bytes'
##            Contentx,Postx      =   self.win.MultiPart([],[['torrent_file',TorrentFile,fdata]],'torrent')
##            if Contentx == None and Postx == None   :   raise Exception
##            print str(Contentx)
##            print 'Post Post-Data is :' + str(len(Postx)) +' Bytes'
##
##            f=open(LookDir + 'test.txt','wb')
##            for i in Postx :
##                f.write(i)
##            f.close()
##            
##            ## Now Action the command..?action=add-file
##            Response            =   self.win.UrlThread(self.FullUrl    +   '?action=add-file'                   ,   \
##                                                       post=Postx                                               ,   \
##                                                       login=self.Login                                         ,   \
##                                                       timeout=int(self.win.Config[self.Title]['TIMEOUT'])      ,   \
##                                                       xContent=Contentx)
##            if Response ==  None    :   raise Exception
##            else                    :   return True
##            self.win.xPrint('++SendTorrent')
##        except  :
##            traceback.print_exc()
##            self.win.xPrint('==SendTorrent')
##            return False

    def SendTorrent(self,LookDir,TorrentFile):
        try :
            self.win.xPrint('--SendTorrent')

            ## Check that the WebServer is Enabled. If not display message and return True..
            if self.win.XbmcWeb ==  None    :
                self.win.Menu.ok(_[83],_[84],_[85])
                return True
            else                            :
                WebUrl      =   str(self.win.XbmcWeb) + 'TmpTor.Torrent'
                
            ## Copy File over to webdir, but remove if it exists already..
            TmpFile         =   str(self.win.WebDir) +'TmpTor.torrent'
            realfile        =   LookDir + TorrentFile
            if os.path.isfile(TmpFile)  :
                os.remove(TmpFile)
            shutil.copy(str(realfile),str(TmpFile))

            ## Now Action the command..?action=add-file
            ActionUrl   =   str(self.FullUrl) + '?action=add-url&s='+ str(WebUrl) +  '&list=1'

            Response    =   self.win.UrlThread(ActionUrl                                                ,   \
                                               login=self.Login                                         ,   \
                                               timeout=int(self.win.Config[self.Title]['TIMEOUT']))
            if Response ==  None    :   raise Exception
            else                    :   return True
            self.win.xPrint('++SendTorrent')
        except  :
            traceback.print_exc()
            self.win.xPrint('==SendTorrent')
            return False
